import {
  DataSet,
  Table,
  Icon,
  Spin,
} from 'choerodon-ui/pro';
import Record from 'choerodon-ui/pro/lib/data-set/Record';
import { Renderer, RenderProps } from "choerodon-ui/pro/lib/field/FormField";
import { Buttons, expandIconProps } from 'choerodon-ui/pro/lib/table/Table';
import { TableMode, TableButtonType } from 'choerodon-ui/pro/lib/table/enum';
import React, { useMemo, MouseEventHandler } from 'react';
import axios from 'axios';
import classNames from 'classnames';
import styles from './index.less';
import TreeDs from './treeDataSet';

const { Column } = Table;

interface Item {
  parentId: number,
  id: number,
}
// @ts-ignore
const iconRenderer: React.FC<RenderProps> = ({ record, text }: RenderProps): Renderer => {
  // @ts-ignore
  return [<Icon key="icon" type={record.get('icon')} />, <span key="text">{text}</span>];
};

const expandedRowRenderer = ({ record }: { record: Record }) => {
  return (
    <p style={{ display: 'none' }}>
      功能代码：{record.get('functionCode')} 入口页面：{record.get('url')}
    </p>
  );
};

// icon 渲染问题， 首先判断record的值和自定义状态来判断出叶节点和父节点进行不同的渲染
const expandicon = ({ prefixCls, expanded, expandable, record, onExpand }: expandIconProps): React.ReactElement => {
  if (record.get('parentId')) {
    // 子结点渲染
    return (<span style={{ paddingLeft: '0.18rem' }} />);
  }

  if (record.getState('loadding') === true) {
    // 自定义状态渲染
    // @ts-ignore
    return (<Spin tip="loding" delay={200} size="small" />);
  }
  const iconPrefixCls = `${prefixCls}-expand-icon`;
  const classString = classNames(iconPrefixCls, {
    [`${iconPrefixCls}-expanded`]: expanded,
  });
  return (<Icon type="baseline-arrow_right" className={classString} onClick={onExpand as MouseEventHandler} tabIndex={expandable ? 0 : -1} />);
};


const treeTableAsync: React.FC = (): React.ReactElement => {
  const dataSetTree = useMemo(() => new DataSet(TreeDs()), []);

  const buttons: Buttons[] = [
    TableButtonType.save,
    TableButtonType.delete,
    TableButtonType.remove,
    TableButtonType.query,
  ];

  // 点击展开
  const handleExpand = (expanded: boolean, record: Record) => {
    const thisParentId = record.get('id');
    // 判断节点是否异步加载子结点
    if (expanded && !record.children) {
      record.setState('loadding', true);
      axios.post('/_api/tree/table/async').then((res) => {
        const data:object[] = dataSetTree.toData();
        let remianData:object[] = [];
        // 如果想全部子结点更新可以使用下面的方法
        if (record.children) {
          // @ts-ignore
          remianData = data.filter((recorditem: Item) => {
            return record?.children?.every((item: Record) => {
              if (thisParentId === item.get('parentId')) {
                return recorditem.id !== item.get('id');
              }
              return true;
            });
          });
        } else {
          remianData = data;
        }
        // 获取子结点数据，绑定父节点
        // @ts-ignore
        const recordsChildren = res.content.map((item: Item) => {
          const newitem = item;
          newitem.parentId = thisParentId;
          newitem.id = Math.random() * 100;
          return newitem;
        });
        record.setState('loadding', false);
        // 生成完成的dataSet数据注意会触发load event
        dataSetTree.loadData([...remianData, ...recordsChildren]);
      }).catch((err) => {
        console.log(err);
        record.setState('loadding', false);
      });
    }
  };

  // expandIcon 渲染图标
  // expandedRowRenderer 这里保证可以触发节点的onExpand 事件
  return (
    <Table
      className={styles.contain}
      mode={TableMode.tree}
      onExpand={handleExpand}
      buttons={buttons}
      dataSet={dataSetTree}
      rowHeight={40}
      expandIcon={expandicon}
      expandedRowRenderer={expandedRowRenderer}
    >
      <Column name="text" editor renderer={iconRenderer} width={450} />
      <Column name="url" editor />
      <Column name="ischecked" editor />
      <Column name="expand" />
    </Table>
  );
};

export default treeTableAsync;



